# cmd['mount'] %("toto", "titi")


# prompt.X_present() => true/false si X tourne
# prompt.X_prompt("question") => pop une textbox
#    et renvoi son contenu (pour demander la size)

#import prompt
import os.path
import commands
import pwd
import grp
import commands, os, string
from Tkinter import *

def X_present():
    """
    teste la presence de X sur la machine
    """
    output = commands.getoutput("ps -e |grep X")
    proginfo = string.split(output)
    if (len(proginfo) >= 4) and (proginfo[3] == 'Xorg' or proginfo[3] == "X"):
        return True
    else:
        return False

def makeentry(parent, caption, width=None, **options):
    Label(parent, text=caption).pack(side=LEFT)
    entry = Entry(parent, **options)
    if width:
        entry.config(width=width)
        entry.pack(side=LEFT)
    return entry


def X_promp(prompt):
    """
    pop une fenetre
    """
    master = Tk()

    h = 100
    w = 200
    ws = master.winfo_screenwidth()
    hs = master.winfo_screenheight()
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    master.geometry('%dx%d+%d+%d' % (w, h, x, y))

    def callback():
        master.quit()

    t = Label(master, text="", fg="yellow")
    t.pack()

    e = Entry(master, width=20)
    e.pack()

    txt = Label(master, text=prompt, fg="yellow")
    txt.pack()

    b = Button(master, text="OK", width=10, command=callback)
    b.pack()

    mainloop()
    return (e.get())

cmd = { "mount":'truecrypt /home/%s/.cont /home/%s/pampam --password="4242pamoulox2424" --keyfiles="" --protect-hidden="no" --fs-options="uid=%s,gid=%s"',
        "umount" : 'truecrypt -d /home/%s/.cont',
        "create" : 'truecrypt -t --create --volume-type="normal" --encryption="AES" --hash="SHA-512" --password="4242pamoulox2424" --filesystem="FAT" --keyfiles="" --random-source="/dev/urandom" /home/%s/.cont --size=%s',
        "mkdir"  : 'mkdir /home/%s/pampam',
        "chown"  : 'chown %s:%s /home/%s/pampam'
        }

class TCrypt:
  def __init__(self):
    """
    initialisation
    """
    pass

  def create_folder(self, *args, **kwargs):
    """
    Creation du dossier si non existant
    """
    pwnam = kwargs["pwn"]
    ret = "Already here"
    if (os.path.exists('/home/' + kwargs["pamh"].user + '/pampam')):
      pass
    else:
      ret = commands.getoutput(cmd['mkdir'] %(kwargs["pamh"].user))
    return ret

  def unmount(self, *args, **kwargs):
    """
    demonter le device
    """
    ret = commands.getoutput(cmd['umount'] %(kwargs["pamh"].user))
    return ret

  def create(self, *args, **kwargs):
    """
    creer le device
    """
    size = user_input(kwargs["pamh"], "Taille du volume (en bytes >= 1000000) ?")
    commands.getoutput(cmd['create'] %(kwargs["pamh"].user, size))

  def mount(self, *args, **kwargs):
    """
    monter le device, le creer si n'existe pas
    """
    self.create_folder(pamh=kwargs["pamh"], pwn=kwargs["pwn"])
    pwnam = kwargs["pwn"]
    if (os.path.exists('/home/' + kwargs["pamh"].user + '/.cont')):
      pass
    else:
      self.create(pamh=kwargs["pamh"])
    ret = commands.getoutput(cmd['mount'] %(kwargs["pamh"].user, kwargs["pamh"].user, pwnam.pw_uid, pwnam.pw_gid))
    return ret

def user_input(pamh, prompt):
    try:
        m = pamh.Message(2, prompt)
        reply = pamh.conversation(m)
    except all as e:
        print "EX"
        raise e
    return reply.resp

def pam_sm_open_session(pamh, flags, args):
    t = TCrypt()
    pwnam = pwd.getpwnam(pamh.user)
    t.mount(pamh=pamh, pwn=pwnam)
    return pamh.PAM_SUCCESS

def pam_sm_close_session(pamh, flags, args):
    t = TCrypt()
    t.unmount(pamh=pamh)
    return pamh.PAM_SUCCESS

def pam_sm_chauthtok(pamh, flags, args):
    w()
    return pamh.PAM_SUCCESS

def pam_sm_authenticate(pamh, flags, args):
    return pamh.PAM_SUCCESS

def pam_sm_setcred(pamh, flags, args):
    return pamh.PAM_SUCCESS

def pam_sm_acct_mgmt(pamh, flags, args):
    return pamh.PAM_SUCCESS

#pam_sm_chauthtok()

